package com.sentiment.nlpalgo.method;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;

import com.sentiment.nlpalgo.bean.Cluster;
import com.sentiment.nlpalgo.bean.Comments;

import org.apache.http.impl.client.DefaultHttpClient;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/*
 * @author liaozhenlin
 * @email 939899727@qq.com
 * 
 */


/*
 * 通过调用相关接口，获得文本分析结果
 * 多文本分析：聚类分析和典型意见分析
 * 聚类分析：
 * 典型意见：
 */

public class TextHttp {
	public static final String X_TOKEN="ouFY-S7c.3495.9mpe6aMSZIoM";
	public static final String CLUSTER_URL_PUSH="http://api.bosonnlp.com/cluster/push/";
	public static final String CLUSTER_URL_STATUS="http://api.bosonnlp.com/cluster/status/";
	public static final String CLUSTER_URL_ANALYSIS="http://api.bosonnlp.com/cluster/analysis/";
	public static final String CLUSTER_URL_RESULT="http://api.bosonnlp.com/cluster/result/";
	public static final String CLUSTER_URL_CLEAR="http://api.bosonnlp.com/cluster/clear/";
	
	public static final String COMMENTS_URL_PUSH="http://api.bosonnlp.com/comments/push/";
	public static final String COMMENTS_URL_STATUS="http://api.bosonnlp.com/comments/status/";
	public static final String COMMENTS_URL_ANALYSIS="http://api.bosonnlp.com/comments/analysis/";
	public static final String COMMENTS_URL_RESULT="http://api.bosonnlp.com/comments/result/";
	public static final String COMMENTS_URL_CLEAR="http://api.bosonnlp.com/comments/clear/";
    
	private String current_task_id;
	private String current_task_url;
	
	public void generateTaskID(){
		Date date = new Date();
		current_task_id = "cyber"+date.toString().replaceAll("[ :]", "").toLowerCase();
	}
	
	public void generateCUrl(String url){
		current_task_url =  url + current_task_id;
	}
	
	
	public void commentsPush(ArrayList<String> list){
		generateCUrl(COMMENTS_URL_PUSH);
		JSONArray array = new JSONArray();
		Iterator it = list.iterator();
		int i=0;
		while(it.hasNext()){
			JSONObject obj = new JSONObject();
			obj.put("_id", i+1);
			i++;
			String str = (String)it.next();
			
			obj.put("text", str);
			array.add(obj);
		}
		
		String jsonString = array.toString();
		htPost(jsonString,current_task_url);
	}
	
	public void clusterPush(ArrayList<String> list){
		generateCUrl(CLUSTER_URL_PUSH);
		JSONArray array = new JSONArray();
		int i=0;
		Iterator it = list.iterator();
		while(it.hasNext()){
			JSONObject obj = new JSONObject();
			obj.put("_id", i+1);
			i++;
			String str = (String)it.next();
			
			obj.put("text", str);
			array.add(obj);
		}
		
		String jsonString = array.toString();
		htPost(jsonString,current_task_url);
	}
	
	public String htGet(String url){
		String jsonString = "";
		HttpGet getMethod = new HttpGet(url); 
		getMethod.addHeader("Accept","application/json");
		getMethod.addHeader("X-Token",X_TOKEN);
		HttpClient httpClient = new DefaultHttpClient(); 
		try { 
		    HttpResponse response = httpClient.execute(getMethod);            //发起GET请求 
		    int code = response.getStatusLine().getStatusCode();         //获取返回code
			if (code == 200) {                                           //成功
		        HttpEntity httpEntity=response.getEntity();
		        BufferedReader bufferedReader=null;
		        StringBuilder entityStringBuilder=new StringBuilder();
		        if (httpEntity!=null) {
		        	
	                bufferedReader=new BufferedReader
	                		(new InputStreamReader(httpEntity.getContent(), "UTF-8"), 8*1024);
	                String line=null;
	                while ((line=bufferedReader.readLine())!=null) {
	                       entityStringBuilder.append(line);
	                }
	                	                
	                jsonString = entityStringBuilder.toString();
	                System.out.println(jsonString);
	            }
		    }else{
		    	System.out.println("网络链接出错，请查看相关代码等"+code);
		    }
		} catch (ClientProtocolException e) { 
		// TODO Auto-generated catch block 
		e.printStackTrace(); 
		} catch (IOException e) { 
		// TODO Auto-generated catch block 
		e.printStackTrace(); 
		} 
		return jsonString;
	}
	
	public ArrayList<Comments> htGetResultComments(String jsonString){
		ArrayList<Comments> array = new ArrayList();
		ArrayList<String> list;
		JSONArray jsarray = JSONArray.fromObject(jsonString);
		Iterator it = jsarray.iterator();
		while(it.hasNext()){
			
			JSONObject obj = (JSONObject)it.next();
			int id = obj.getInt("_id");
			String str = obj.getString("list");
			JSONArray jstr = JSONArray.fromObject(str);
			list = new ArrayList();
			Iterator it2 = jstr.iterator();
				while(it2.hasNext()){
					JSONArray temp = (JSONArray)it2.next();
					String stemp = temp.getString(0);
					list.add(stemp);
				}
				
			int num = obj.getInt("num");
			String opinion = obj.getString("opinion");
			Comments comments = new Comments(id,opinion,list,num);
			array.add(comments);
		}
		return array;	
	}
		
	
	
	/*
     * 该函数使用HttpClient进行网络资源访问
     * entity:传人一个具体的正文内容 可以是json类型
     * urlString ：地址
     */
	public String htPost(String entity,String urlString){
		String jsonString = "";
		HttpClient client = new DefaultHttpClient();                     //生成一个HttpClient对象
		HttpPost httpPost=new HttpPost(urlString);                       //采用post方法传输数据。
		                                                                 //urlString为一个具体地址的url
		httpPost.addHeader("Content-Type","application/json");           //添加Http协议的Header
		httpPost.addHeader("Accept","application/json");
		httpPost.addHeader("X-Token", X_TOKEN);                          //?为一系列的字符组成，是API的密钥
		
		httpPost.setEntity(new StringEntity(entity,"UTF-8"));    
	    HttpResponse response;                                           //定义HttpResponse
	    try {
			response = client.execute(httpPost);                         //执行post请求
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}                     
	    
		return jsonString;
	}
	
	public String getCurrent_task_id() {
		return current_task_id;
	}

	public void setCurrent_task_id(String current_task_id) {
		this.current_task_id = current_task_id;
	}
	
	/*
	 * 调用文本聚类算法
	 * 输入list为文本队列
	 * 返回聚类基本信息
	 */
	public ArrayList<Cluster> cluster(ArrayList<String> list){
		ArrayList<Cluster> arrayList = new ArrayList();
		generateTaskID();
		//textHttp.setCurrent_task_id("MonSep21213026CST2015");
		clusterPush(list);
		String urlana = CLUSTER_URL_ANALYSIS + current_task_id;
		String urlst =  CLUSTER_URL_STATUS + current_task_id;
		htGet(urlana);
		while(true){
			if(htGet(urlst).contains("DONE")){
				String urlre =  CLUSTER_URL_RESULT + current_task_id;
		        String strht = htGet(urlre);
		        JSONArray array = JSONArray.fromObject(strht);
		        Iterator it = array.iterator();
		        while(it.hasNext()){
		        	JSONObject obj = (JSONObject) it.next();
		        	JSONArray arr = (JSONArray)obj.getJSONArray("list");
		        	ArrayList<Integer> list_temp = new ArrayList();
		        	Iterator it2 = arr.iterator();
		        	while(it2.hasNext()){
		        		list_temp.add((Integer)it2.next());
		        	}
		        	Cluster clu = new Cluster(obj.getInt("_id"),obj.getInt("num"),list_temp);
		        	arrayList.add(clu);
		        }
		        String urlcl = CLUSTER_URL_CLEAR + current_task_id;
		        htGet(urlcl);
		        break;
			}else{
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
		System.out.println(arrayList);
		return arrayList;
		
	}
	
	/*
	 * 调用典型意见分析算法
	 * 输入list为评论队列
	 * 返回队列基本信息
	 */
	public ArrayList<Comments> comments(ArrayList<String> list){
		generateTaskID();
		//textHttp.setCurrent_task_id("MonSep21213026CST2015");
		commentsPush(list);
		String urlana = COMMENTS_URL_ANALYSIS + current_task_id;
		String urlst =  COMMENTS_URL_STATUS + current_task_id;
		ArrayList<Comments> arc = new ArrayList();
		htGet(urlana);
		while(true){
			if(htGet(urlst).contains("DONE")){
				String urlre =  COMMENTS_URL_RESULT + current_task_id;
		        String strj = htGet(urlre);
		        arc = htGetResultComments(strj);
		        String urlcl = COMMENTS_URL_CLEAR + current_task_id;
		        
		        htGet(urlcl);
		        break;
			}else{
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
		return arc;
	}
	
	

	
	public static void main(String[] args){
		
		
		ArrayList<String> list = new ArrayList();
		for(int i = 0 ;i < 10 ; i++){
			JSONObject obj = new JSONObject();
			obj.put("_id", i+1);
			String str = "例如，对某款香水的评论进行典型意见分析，会得到如下结果："
					+ "味道很女人的(256类似)，瓶子的设计也很漂亮了(237类似)，"
					+ "留香时间很长(156类似)。";
			
			list.add(str);
		}
		TextHttp textHttp = new TextHttp();
		textHttp.cluster(list);
//		textHttp.comments(list);
//		textHttp.generateTaskID();
//		//textHttp.setCurrent_task_id("MonSep21213026CST2015");
//		textHttp.clusterPush();
//		try {
//			Thread.sleep(3000);
//		} catch (InterruptedException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		String urlana = CLUSTER_URL_ANALYSIS + textHttp.getCurrent_task_id();
//		String urlst =  CLUSTER_URL_STATUS + textHttp.getCurrent_task_id();
//        
//		textHttp.htGet(urlana);
//		textHttp.htGet(urlst);
//		try {
//			Thread.sleep(5000);
//		} catch (InterruptedException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		
//	    
//		String urlre =  CLUSTER_URL_RESULT + textHttp.getCurrent_task_id();
//        textHttp.htGet(urlre);
//        String urlcl = CLUSTER_URL_CLEAR + textHttp.getCurrent_task_id();
//        textHttp.htGet(urlcl);
		
	}
}
